import { useModel } from 'umi';
import React, { useRef, useEffect, useState } from 'react';
import {
  Row,
  Col,
  Tree,
  message,
  Card,
  Space,
  Button,
  Drawer,
  Checkbox,
  Tooltip,
  Spin,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, {
  ProFormText,
  ProFormSwitch,
  ProFormDigit,
  ProFormTreeSelect,
  ProFormSelect,
} from '@ant-design/pro-form';
import {
  add,
  del,
  update,
  getOrgTree
} from './service';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import AuthorityButton from '@/components/AuthorityButton';
import { CarryOutOutlined, FormOutlined } from '@ant-design/icons';
const Menu = () => {
  const { initialState } = useModel('@@initialState');
  const formActionRef = useRef();
  const formRef = useRef();
  const [currentOrg, SetCurrentOrg] = useState();
  const [state, setState] = useState('read');
  const [treeData, SetTreeData] = useState([]);
  const [cardTitle, SetCardTitle] = useState('详情');
  //drawer 显示控制
  const [drawerVisible, setDrawerVisible] = useState(false);

  //初始化数据
  useEffect(() => {
    const initData = async (value) => {
      await getOrgTree().then((re) => {
        if (re.isSuccess) {
          SetTreeData(re.data);
        }
      });
    };
    initData();
  }, []);

  //获取菜单数据
  const getOrgTreeList = async () => {
    await getOrgTree().then((r) => {
      if (r.isSuccess) {
        SetTreeData(r.data);
      }
    });
  };
  const onSelect = (keys, info) => {
    setState('read');
    info.node.id = info.node.key;
    info.node.name = info.node.title;
    SetCurrentOrg(info.node);
    formRef?.current?.setFieldsValue(info.node);
  };

  const loopItem = (value) =>
    value?.map((item, index) => {
      return {
        parentId: item.parentId,
        key: item.key,
        title: item.title,
        label: item.title,
        value: item.key,
        info: item,
        children: item.children && loopItem(item.children),
      };
    });



  return (
    <PageContainer>
      <Row gutter={16}>
        <Col span={18} push={6}>
          <Card
            title={cardTitle}
            extra={
              <Space>
                <Button
                  style={{ display: currentOrg ? 'block' : 'none' }}
                  type="primary"
                  onClick={() => {
                    setState('edit');
                    SetCardTitle('修改');
                  }}
                >
                  修改
                </Button>
                <Button
                  onClick={() => {
                    setState('edit');
                    SetCurrentOrg(undefined);
                    formRef.current.resetFields(undefined);
                    SetCardTitle('新增');
                  }}
                >
                  新增
                </Button>
              </Space>
            }
          >
            <ProForm
              formRef={formRef}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              layout={'horizontal'}
              submitter={
                state == 'read'
                  ? false
                  : {
                    render: (props, doms) => {
                      return (
                        <Row>
                          <Col span={16} offset={8}>
                            <Space>{doms}</Space>
                          </Col>
                        </Row>
                      );
                    },
                  }
              }
              onFinish={async (values) => {
                var res = { isSuccess: false };
                res = currentOrg ? await update(values) : await add(values);
                if (res.isSuccess) {
                  getOrgTreeList();
                  currentOrg ? SetCurrentOrg(values) : SetCurrentOrg(res.data);
                  setState('read');
                  SetCardTitle('详情');
                  message.success(res.msg);
                } else {
                  message.error(res.msg);
                }
              }}
            >
              <ProFormText name="id" hidden />
              <ProFormText
                mode={state}
                name="name"
                width="md"
                label="组织名称"
                placeholder="组织名称"
              />
              <ProFormTreeSelect
                mode={state}
                name="parentId"
                width="md"
                label="上级组织"
                placeholder="上级组织"
                request={() => {
                  var data = [{ key: 0, title: '顶层', value: 0, label: '顶层' }];
                  return [...data, ...loopItem(treeData)];
                }}
              />
            </ProForm>
          </Card>
        </Col>
        <Col span={6} pull={18}>
          {treeData.length > 0 ? (<Tree
            showIcon
            defaultExpandAll={true}
            height={600}
            onSelect={onSelect}
            treeData={loopItem(treeData)}
            titleRender={(nodeData) => {
              return (
                <Space size={'large'}>
                  {nodeData.title}
                  <Space style={{ float: 'right' }}>
                    <AuthorityButton
                      type={'popconfirm'}
                      key="del"
                      class={'delete'}
                      text={
                        <Tooltip placement="topLeft" title="删除">
                          <DeleteOutlined />
                        </Tooltip>
                      }
                      onConfirm={() => {
                        del([nodeData.key]).then((re) => {
                          if (re.isSuccess) {
                            getOrgTreeList();
                            message.success(re.msg);
                          } else {
                            message.error(re.msg);
                          }
                        });
                      }}
                    />
                  </Space>
                </Space>
              );
            }}
          />) : ''}

        </Col>
      </Row>
      ,
    </PageContainer>
  );
};

export default Menu;
